<template>
    <div style="border: 2px dotted lightblue;width: 800px; height: 500px;margin: 0 auto;">
        <div style="margin-top: 250px;">
            <el-upload class="upload-demo" ref="upload" action="http://localhost:3000/uploadimg" :headers='header'
                :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false"
                list-type="picture" multiple :on-success="
            (response, file, fileList) => {
              return handleSuccess(response, file, fileList);
            }">
                <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" @click="show(file)">
                    <span>name:{{ file.name }}</span>
                    <span style="margin-left: 15px;">size:{{ file.size }}</span>
                </div>
                <el-button slot="trigger" size="small" type="primary">选择照片</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">提交</el-button>
            </el-upload>
            <el-dialog :title="提示" :visible.sync="dialogVisible" :before-close="handleClose" width='30%'>
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            <el-pagination small layout="prev, pager, next" :total="50">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                fileList: [],
                dialogVisible: false,
                disabled: false,
                dialogImageUrl: '',
                header: { 'authorization': localStorage["token"] },
                total: ''
            };
        },
        methods: {
            submitUpload() {
                this.$refs.upload.submit();
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            handleSuccess(response, file, fileList) {
                console.log(response, file, fileList);

            },
            // httpRequest(params) {
            //   console.log(localStorage["token"]);
            //   console.log(params)//拿到上传的文件
            //   fetch("http://localhost:3000/uploadimg", {
            //     method: 'POST',
            //     body: JSON.stringify(params.file),
            //     headers: { 'authorization': localStorage["token"] }
            //   }).then(res => res.json())
            //     .then(res => {
            //       if (res.token) {
            //         alert('文件上传成功')
            //       } else {
            //         alert('文件上传失败')
            //       }
            //     })
            // },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => { });
            },
            show(file) {
                this.dialogVisible = true;
                this.dialogImageUrl = file.url;
            },
            getpage() {
                fetch("http://localhost:3000/getpage")
                    .then(res => res.json())
                    .then(res => {
                        console.log(res.length);
                        this.total = res.length;
                    })
            }
        },
        mounted() {
            this.getpage();
        }
    }
</script>

<!-- const router = require('koa-router')()
var svgCaptcha = require('svg-captcha');
const jwt = require("jsonwebtoken")
const mykey = "uwafnskzjnfal@"
const formidable = require("formidable");
const path = require('path')
const fs = require('fs')
const dirPath = path.join(path.resolve(__dirname, '../'), '/public/images')

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        title: 'Hello Koa 2!'
    })
})
router.get("/captcha", async (ctx, next) => {
    var captcha = svgCaptcha.create();
    ctx.session.captcha = captcha.text;
    ctx.body = captcha.data;
})
router.post("/login", async (ctx, next) => {
    console.log(ctx.request.body);
    console.log(ctx.session);
    let token = jwt.sign({ name: ctx.request.body.userName }, mykey);
    ctx.body = { token: token }
})

// 图片上传
const uploadImg = (ctx) => {
    const form = formidable({
        multiples: true,
        uploadDir: dirPath,
        keepExtensions: true,
        allowEmptyFiles: false
    });

    return new Promise((resolve, reject) => {
        form.parse(ctx.req, (err, fields, files) => {
            //ctx.req原生的node的http请求模块；ctx.require.body是经过koa二次封装之后的
            if (err) {
                reject(err);
                return;
            }
            let keys = Object.keys(files);//获取files对象中的属性名[formData传入的图片]
            keys?.map((key) => {
                console.log(key);
                // 将文件重命名为原本的文件名
                // fs.rename(path.join(dirPath, `/${files[key].newFilename}`), path.join(dirPath, `/${files[key].originalFilename}`),
                // (err) => {
                // if (err) {
                // console.log(err);
                // } else {
                // console.log('file is reset!');
                // }
                // })
            })
            resolve({ ok: true, fields, files });
        });
    });
}



// 校验
router.post('/uploadimg', async (ctx, next) => {
    // let token = ctx.req.headers.authorization;
    // console.log(token);
    // let result = jwt.verify(token, mykey);
    // ctx.body = { token: result };
    ctx.body = await uploadImg(ctx);
})
router.get("/getpage", async (ctx, next) => {
    let pageList = fs.readdirSync(dirPath)
    ctx.body = { pageList };
})
router.get('/string', async (ctx, next) => {
    ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
    ctx.body = {
        title: 'koa2 json'
    }
})

module.exports = router -->